﻿package com.dbm.model;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.dbm.dao.CtlPublicDao;
import com.dbm.dao.CtlSellSoInfoDao;
import com.dbm.dao.CtlSoInfoDao;
import com.dbm.dao.LsDao;
import com.dbm.dao.OrderProcessDao;
import com.dbm.dao.WmsSellSoInfoDao;
import com.dbm.dao.WmsSoInfoDao;
import com.dbm.util.JaxbUtil;
import com.dbm.util.LsInfo;
import com.dbm.util.OrderProcess;
import com.dbm.util.PackageInfo;
import com.dbm.util.PackageItem;
import com.dbm.util.Response;
import com.dbm.util.SellSoInfoUtil;
import com.dbm.util.SoInfo;


/**
 * 发货单转wms发运订单逻辑处理
 * 
 * @author wqying
 * 
 */
public class SellSoModel {
	Logger log = Logger
			.getLogger(SellSoModel.class);
	CtlSellSoInfoDao ctlSellSoInfoDao = new CtlSellSoInfoDao();
	WmsSellSoInfoDao wmsSellSoInfoDao = new WmsSellSoInfoDao();
	CtlPublicDao ctlPublicDao = new CtlPublicDao();
	WmsSoInfoDao wmssoDao = new WmsSoInfoDao();
	private WmsToOrderProcess wmsToOrderProcess = new WmsToOrderProcess();
	CtlSoInfoDao ctlSoDao = new CtlSoInfoDao();
	private OrderProcessDao orderProcessDao = new OrderProcessDao();
	private String param = "";
	private CtlHttp ctlHttp = new CtlHttp();
	private LsDao lsDao = new LsDao();
	private SendLsPost sendLsPost = new SendLsPost();
	private JudgeParam judgeParam = new JudgeParam();
	/**
	 * 完全发货处理逻辑-多运单号多包裹明细
	 */
	public synchronized void reSellInfoPackage() {
		try {
			List<String> soreference1s = wmsSellSoInfoDao
					.getAllReturnSoreferenceInfoPackage();
			for (String soreference1 : soreference1s) {
				List<SellSoInfoUtil> wmsSellSoInfoUtils = wmsSellSoInfoDao
						.getReturnSoInfoFromWmsPackage(soreference1);
				// sSystem.out.println(wmsSellSoInfoUtils.size());
				if (wmsSellSoInfoUtils.size() > 0) {
					List<SellSoInfoUtil> CtlSellSoInfoUtils = new ArrayList<SellSoInfoUtil>();
					for (SellSoInfoUtil sellSoInfo : wmsSellSoInfoUtils) {
						// String deliveryOrderId =
						// ctlSellSoInfoDao.getdeliveryOrderId(soreference1);
						// sellSoInfo.setDELIVERYORDERID(deliveryOrderId);
						// List<SellSoInfoUtil> sellSoInfoUtils =
						// ctlSellSoInfoDao.getSellSoInfoUtilsById(sellSoInfo);
						sellSoInfo = ctlSellSoInfoDao
								.getSellSoInfoUtilsBySellSoInfo(sellSoInfo);
						sellSoInfo.setSTATUS("DELIVERED");
						sellSoInfo.setSENDFLAG("NO");
						sellSoInfo.setDESTINATION("QM");
						sellSoInfo.setCONFIRMTYPE(new BigDecimal(0));
						CtlSellSoInfoUtils.add(sellSoInfo);
					}
					String newdeliveryOrderId = "FH"
							+ ctlPublicDao
									.getEntryOrderIdBySeq("seqSellDeliveryOrderInfo");
					ctlSellSoInfoDao.addCtlSoFhdHeader(
							CtlSellSoInfoUtils.get(0), newdeliveryOrderId);
					ctlSellSoInfoDao.addSellDetails(CtlSellSoInfoUtils,
							newdeliveryOrderId);
					List<PackageInfo> packageInfos = wmsSellSoInfoDao
							.getAllPackageInfo(soreference1);
					for (PackageInfo packageInfo : packageInfos) {
						String packageId = ctlPublicDao
								.getEntryOrderIdBySeq("SEQPACKAGEINFO");
						log.info("SellsoModel获取到的packageid：" + packageId);
						ctlSellSoInfoDao.addPackageInfo(packageInfo, packageId,
								newdeliveryOrderId);
						List<PackageItem> packageItems = wmsSellSoInfoDao
								.getPackageItemByPackageInfo(packageInfo);
						for (PackageItem packageItem : packageItems) {
							String packageItemId = ctlPublicDao
									.getEntryOrderIdBySeq("SEQPACKAGEITEM");
							ctlSellSoInfoDao.addPackAgeItem(packageItem,
									packageItemId, packageId);
						}
					}

					log.info("完全发货，新增CTL 数据" + newdeliveryOrderId);
					param = "method=deliveryorder.confirm&sign=NO&msg="
							+ newdeliveryOrderId;
					String result = ctlHttp.getHttpResult(param);// 向ctl发送 发货确认HTTP
					if (!"".equals(result)) {
						JaxbUtil jaxbUtil = new JaxbUtil(Response.class);
						Response response = jaxbUtil.fromXml(result);
						response.setOwnercode(wmsSellSoInfoUtils.get(0).getOWNERCODE());
						response.setWarehouseId(wmsSellSoInfoUtils.get(0).getWAREHOUSECODE());
						wmsSellSoInfoDao.addEdiInfo(response, soreference1);
						log.info("发运订单确认返回报文：" + result);
						log.info("进入发运订单，数据处理成功，id：" + newdeliveryOrderId);
					} else {
						ctlPublicDao.addCtlErrorHttpPost(param);
						log.error("发运确认请求发送失败，httppost参数已经记录ctl层数据库的ERRORHTTPPOST表");
					}
					String orderNo = wmsSellSoInfoDao
							.getSoNoBySoreference1(soreference1);
					// System.out.println(orderNo+"\t"+soreference1);
					System.out.println("系统重置标记："
							+ wmsSellSoInfoDao.updateSoHeaderSendFlag("Y",
									orderNo));
					if (wmsSellSoInfoUtils.size() != 0)
						log.info("单号:" + soreference1 + "完全发货，确认处理成功");
				}
			}
		} catch (Exception e) {
			log.info("完全发货确认处理失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 完全发货处理逻辑
	 */
	public synchronized void reSoInfoEnd() {
		try {
			List<String> soreference1s = wmsSellSoInfoDao
					.getAllReturnSoreferenceInfo();
			for (String soreference1 : soreference1s) {
				List<SellSoInfoUtil> wmsSellSoInfoUtils = wmsSellSoInfoDao
						.getReturnSoInfoFromWmsEnd(soreference1);
				// sSystem.out.println(wmsSellSoInfoUtils.size());
				if (wmsSellSoInfoUtils.size() > 0) {
					List<SellSoInfoUtil> CtlSellSoInfoUtils = new ArrayList<SellSoInfoUtil>();
					for (SellSoInfoUtil sellSoInfo : wmsSellSoInfoUtils) {
						// String deliveryOrderId =
						// ctlSellSoInfoDao.getdeliveryOrderId(soreference1);
						// sellSoInfo.setDELIVERYORDERID(deliveryOrderId);
						// List<SellSoInfoUtil> sellSoInfoUtils =
						// ctlSellSoInfoDao.getSellSoInfoUtilsById(sellSoInfo);
						sellSoInfo = ctlSellSoInfoDao
								.getSellSoInfoUtilsBySellSoInfo(sellSoInfo);
						sellSoInfo.setSTATUS("DELIVERED");
						sellSoInfo.setSENDFLAG("NO");
						sellSoInfo.setDESTINATION("QM");
						sellSoInfo.setCONFIRMTYPE(new BigDecimal(0));
						log.info("物流公司编码1：\t" + sellSoInfo.getLOGISTICSCODE());
						CtlSellSoInfoUtils.add(sellSoInfo);
					}
					String newdeliveryOrderId = "FH"
							+ ctlPublicDao
									.getEntryOrderIdBySeq("seqSellDeliveryOrderInfo");
					ctlSellSoInfoDao.addCtlSoFhdHeader(
							CtlSellSoInfoUtils.get(0), newdeliveryOrderId);
					ctlSellSoInfoDao.addSellDetails(CtlSellSoInfoUtils,
							newdeliveryOrderId);
					String packageId = ctlPublicDao
							.getEntryOrderIdBySeq("SEQPACKAGEINFO");
					log.info("物流公司编码2：\t"
							+ CtlSellSoInfoUtils.get(0).getLOGISTICSCODE());
					ctlSellSoInfoDao.addPackageInfo(CtlSellSoInfoUtils.get(0),
							packageId, newdeliveryOrderId);
					for (SellSoInfoUtil sellSoInfo : CtlSellSoInfoUtils) {
						String packageItemId = ctlPublicDao
								.getEntryOrderIdBySeq("SEQPACKAGEITEM");
						ctlSellSoInfoDao.addPackAgeItem(sellSoInfo,
								packageItemId, packageId);
					}
					log.info("完全发货，新增CTL 数据" + newdeliveryOrderId);
					param = "method=deliveryorder.confirm&sign=NO&msg="
							+ newdeliveryOrderId;
					String result = ctlHttp.getHttpResult(param);
					if (!"".equals(result)) {
						log.info("发运订单确认返回报文：" + result);// 向ctl发送 发货确认HTTP
															// 请求，并将返回结果记录到日志中。
						JaxbUtil jaxbUtil = new JaxbUtil(Response.class);
						Response response = jaxbUtil.fromXml(result);
						response.setOwnercode(wmsSellSoInfoUtils.get(0).getOWNERCODE());
						response.setWarehouseId(wmsSellSoInfoUtils.get(0).getWAREHOUSECODE());
						wmsSellSoInfoDao.addEdiInfo(response, soreference1);
						log.info("进入发运订单，数据处理成功，id：" + newdeliveryOrderId);
					} else {
						ctlPublicDao.addCtlErrorHttpPost(param);
						log.error("发运确认请求发送失败，httppost参数已经记录ctl层数据库的ERRORHTTPPOST表");
					}
					String orderNo = wmsSellSoInfoDao
							.getSoNoBySoreference1(soreference1);
					// System.out.println(orderNo+"\t"+soreference1);
					System.out.println("系统重置标记："
							+ wmsSellSoInfoDao.updateSoHeaderSendFlag("Y",
									orderNo));
					if (wmsSellSoInfoUtils.size() != 0)
						log.info("单号:" + soreference1 + "完全发货，确认处理成功");
				}
			}
		} catch (Exception e) {
			log.info("完全发货确认处理失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 处理部分发货确认逻辑，首先从视图中查询所有erp订单号， 然后利用erp订单号，查询该订单号下面的所有已发货的明细
	 * 根据已发货明细，去ctl的视图中查询出ctl中的相关信息 将查询出的信息写入ctl数据库 public synchronized void
	 * reSoInfo(){ try { List<String> soreference1s =
	 * wmsSellSoInfoDao.getAllReturnSoreferenceInfo(); for(String soreference1
	 * :soreference1s){ List<SellSoInfoUtil> wmsSellSoInfoUtils =
	 * wmsSellSoInfoDao.getReturnSoInfoFromWms(soreference1); //
	 * System.out.println(wmsSellSoInfoUtils.size()); for(SellSoInfoUtil
	 * sellSoInfo:wmsSellSoInfoUtils){ String deliveryOrderId =
	 * ctlSellSoInfoDao.getdeliveryOrderId(soreference1);
	 * sellSoInfo.setDELIVERYORDERID(deliveryOrderId); List <SellSoInfoUtil>
	 * sellSoInfoUtils = ctlSellSoInfoDao.getSellSoInfoUtilsById(sellSoInfo);
	 * SellSoInfoUtil sellInfo = sellSoInfoUtils.get(0);
	 * sellInfo.setSTATUS("PARTDELIVERED"); sellInfo.setSENDFLAG("NO");
	 * sellInfo.setDESTINATION("QM"); String newdeliveryOrderId =
	 * "FH"+ctlPublicDao.getEntryOrderIdBySeq("seqSellDeliveryOrderInfo");
	 * ctlSellSoInfoDao.addCtlSoFhdHeader(sellInfo, newdeliveryOrderId);
	 * ctlSellSoInfoDao.addSellDetails(sellSoInfoUtils, newdeliveryOrderId);
	 * String packageId = ctlPublicDao.getEntryOrderIdBySeq("SEQPACKAGEINFO");
	 * String packageItemId =
	 * ctlPublicDao.getEntryOrderIdBySeq("SEQPACKAGEITEM");
	 * ctlSellSoInfoDao.addPackageInfo(sellInfo, packageId, newdeliveryOrderId);
	 * ctlSellSoInfoDao.addPackAgeItem(sellInfo, packageItemId, packageId);
	 * log.info("部分发货，新增CTL 数据"+newdeliveryOrderId); String orderNo =
	 * wmsSellSoInfoDao.getSoNoBySoreference1(soreference1);
	 * wmsSellSoInfoDao.updateSoHeaderSendFlag("7",orderNo);
	 * System.out.println("***********"+orderNo); }
	 * if(wmsSellSoInfoUtils.size()!=0)
	 * log.info("单号:"+soreference1+"部分发货，确认处理成功"); } } catch (Exception e) {
	 * log.info("部分发货确认处理失败！"); e.printStackTrace(); } }
	 */

	public void ThreadSellSoInfoToWms() {
		try {
			List<String> deliveryOrderIds = ctlSellSoInfoDao
					.getAlldeliveryOrderId();
			ctlSellSoInfoToWms(deliveryOrderIds);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("发货单处理失败" + e);
		}

	}

	/**
	 * ctl发货单转wms 发运订单逻辑
	 */
	public synchronized void ctlSellSoInfoToWms(List<String> deliveryOrderIds) {
		for (String deliveryOrderId : deliveryOrderIds) {
		try {
					log.info("获取到ctl层的发货单 ID：\t" + deliveryOrderId);
					SellSoInfoUtil sellSoInfo = new SellSoInfoUtil();
					sellSoInfo.setDELIVERYORDERID(deliveryOrderId);
					String packageId = ctlPublicDao
							.getEntryOrderIdBySeq("SEQPACKAGEINFO");
					String packageItemId = ctlPublicDao
							.getEntryOrderIdBySeq("SEQPACKAGEITEM");
					List<SellSoInfoUtil> sellSoInfoUtils = ctlSellSoInfoDao
							.getSellSoInfoUtilsById(sellSoInfo);
					SellSoInfoUtil sellInfo = sellSoInfoUtils.get(0);
					if (!wmsSellSoInfoDao.judgeOrder(sellInfo.getDELIVERYORDERCODE(),sellInfo.getOWNERCODE())) {//判断订单是否进入wms，防止重复进入。
					if (wmsSellSoInfoDao.addSellSoInfoToWms(sellSoInfoUtils)) {
						sellInfo.setSTATUS("ACCEPT");
						sellInfo.setSENDFLAG("NO");
						sellInfo.setDESTINATION("QM");
						String newdeliveryOrderId = "FH"
								+ ctlPublicDao
										.getEntryOrderIdBySeq("seqSellDeliveryOrderInfo");
						// ctlSellSoInfoDao.addCtlSoFhdHeader(sellInfo,
						// newdeliveryOrderId);
						// ctlSellSoInfoDao.addSellDetails(sellSoInfoUtils,
						// newdeliveryOrderId);
						SoInfo soInfo = new SoInfo();
						soInfo.setLOGISTICSCODE(sellInfo.getLOGISTICSCODE());
						soInfo.setLOGISTICSNAME(sellInfo.getLOGISTICSNAME());
						if (soInfo.getEXPRESSCODE() == null) {// 如果 ERP没有传递运单号的话，将生成测试运单号。
							soInfo.setEXPRESSCODE("Test111222333");
						}
						soInfo.setDELIVERYORDERCODE(sellInfo
								.getDELIVERYORDERCODE());
						soInfo.setORDERTYPE(sellInfo.getORDERTYPE());
						soInfo.setWAREHOUSECODE(sellInfo.getWAREHOUSECODE());
						soInfo.setSTATUS("ACCEPT");
						soInfo.setPACKAGECODE(sellInfo.getPACKAGECODE());
						soInfo.setITEMCODE(sellInfo.getITEMCODE());
						soInfo.setACTUALQTY(sellInfo.getACTUALQTY());
						soInfo.setTHEORETICALWEIGHT(sellInfo
								.getTHEORETICALWEIGHT());
						ctlSoDao.addPackageInfo(soInfo, packageId,
								newdeliveryOrderId);// 新增包裹信息
						ctlSoDao.addPackAgeItem(soInfo, packageItemId,
								packageId);// 新增包裹明细信息
						log.info("仓库接单，新增CTL 数据" + newdeliveryOrderId);
						ctlSellSoInfoDao.upSellFlag(deliveryOrderId);
						log.info("soInfo相关信息：/t" + soInfo);
						OrderProcess orderProcess = wmsToOrderProcess
								.bySoInfo(soInfo);
						orderProcessDao.addOrderProcess(orderProcess);// 仓库接单新增订单流水
						int id = Integer.valueOf(ctlPublicDao
								.getEntryOrderIdBySeq("SEQeLSHTTPPOST"));
						lsDao.addLsParam(id, orderProcess.getID());
						LsInfo lsInfo = new LsInfo();
						lsInfo.setId(id);
						lsInfo.setParam(orderProcess.getID());
						String param = OracleFunctionUtil.getSysConfiguration(orderProcess.getWAREHOUSECODE(), orderProcess.getREMARK(), "TOP_QM_LS");
						if(judgeParam.JudgeWmsParam(param, "Y")){
//						sendLsPost.sendLsPost(lsInfo);
						}
					}
				}else{
					ctlSellSoInfoDao.upSellFlag(deliveryOrderId);//如果订单已经进入wms，防止重复进入扫描到数据，直接更新ctl库标记。
				}
				
		} catch (Exception e) {
			log.error("ctl层的发货单 ：\t" + deliveryOrderId+"进入 wms处理失败。" + e);
			//TODO 将处理失败的发货单记录到数据库中去。尝试人工参与解决。
			/**
			 * 根据目前考虑到的地方，数据库可以记录表名称、人工参与处理的字段名称（sendflag等标记）。以及需要处理的id，
			 * 可以在界面上做出全表内容的展示。
			 */
			//TODO 如果后期上线短信或微信提醒功能的话，可以在每次往数据库写入失败信息的时候发出电信或微信提醒。
			e.printStackTrace();
		}
		}

	}

	/**
	 * ctl发货单转wms 发运订单逻辑---供CTL调用 方式
	 */
	public synchronized String ctlSellSoInfoToWmsUrl(String deliveryOrderId) {
		String result = "订单进入wms成功！";
		try {
					log.info("接收到ctl层的发货单 ID：\t" + deliveryOrderId);
					SellSoInfoUtil sellSoInfo = new SellSoInfoUtil();
					log.info("初始化实例"+SellSoInfoUtil.class+"完成.");
					sellSoInfo.setDELIVERYORDERID(deliveryOrderId);
					String packageId = ctlPublicDao
							.getEntryOrderIdBySeq("SEQPACKAGEINFO");
					String packageItemId = ctlPublicDao
							.getEntryOrderIdBySeq("SEQPACKAGEITEM");
					List<SellSoInfoUtil> sellSoInfoUtils = ctlSellSoInfoDao
							.getSellSoInfoUtilsById(sellSoInfo);
					SellSoInfoUtil sellInfo = sellSoInfoUtils.get(0);
					if (!wmsSellSoInfoDao.judgeOrder(sellInfo.getDELIVERYORDERCODE(),sellInfo.getOWNERCODE())) {//判断订单是否进入wms，防止重复进入。
					if (wmsSellSoInfoDao.addSellSoInfoToWms(sellSoInfoUtils)) {
						sellInfo.setSTATUS("ACCEPT");
						sellInfo.setSENDFLAG("NO");
						sellInfo.setDESTINATION("QM");
						String newdeliveryOrderId = "FH"
								+ ctlPublicDao
										.getEntryOrderIdBySeq("seqSellDeliveryOrderInfo");
						// ctlSellSoInfoDao.addCtlSoFhdHeader(sellInfo,
						// newdeliveryOrderId);
						// ctlSellSoInfoDao.addSellDetails(sellSoInfoUtils,
						// newdeliveryOrderId);
						SoInfo soInfo = new SoInfo();
						soInfo.setLOGISTICSCODE(sellInfo.getLOGISTICSCODE());
						soInfo.setLOGISTICSNAME(sellInfo.getLOGISTICSNAME());
						if (soInfo.getEXPRESSCODE() == null) {// 如果 ERP没有传递运单号的话，将生成测试运单号。
							soInfo.setEXPRESSCODE("Test111222333");
						}
						soInfo.setDELIVERYORDERCODE(sellInfo
								.getDELIVERYORDERCODE());
						soInfo.setORDERTYPE(sellInfo.getORDERTYPE());
						soInfo.setWAREHOUSECODE(sellInfo.getWAREHOUSECODE());
						soInfo.setSTATUS("ACCEPT");
						soInfo.setPACKAGECODE(sellInfo.getPACKAGECODE());
						soInfo.setITEMCODE(sellInfo.getITEMCODE());
						soInfo.setACTUALQTY(sellInfo.getACTUALQTY());
						soInfo.setTHEORETICALWEIGHT(sellInfo
								.getTHEORETICALWEIGHT());
						soInfo.setOWNERCODE(sellInfo.getOWNERCODE());
						ctlSoDao.addPackageInfo(soInfo, packageId,
								newdeliveryOrderId);// 新增包裹信息
						ctlSoDao.addPackAgeItem(soInfo, packageItemId,
								packageId);// 新增包裹明细信息
						log.info("仓库接单，新增CTL 数据" + newdeliveryOrderId);
						ctlSellSoInfoDao.upSellFlag(deliveryOrderId);
						log.info("soInfo相关信息：/t" + soInfo);
						OrderProcess orderProcess = wmsToOrderProcess
								.bySoInfo(soInfo);
						orderProcessDao.addOrderProcess(orderProcess);// 仓库接单新增订单流水
						int id = Integer.valueOf(ctlPublicDao
								.getEntryOrderIdBySeq("SEQeLSHTTPPOST"));
						lsDao.addLsParam(id, orderProcess.getID());
						LsInfo lsInfo = new LsInfo();
						lsInfo.setId(id);
						lsInfo.setParam(orderProcess.getID());
						String param = OracleFunctionUtil.getSysConfiguration(orderProcess.getWAREHOUSECODE(), orderProcess.getREMARK(), "TOP_QM_LS");
						if(judgeParam.JudgeWmsParam(param, "Y"))
						sendLsPost.sendLsPost(lsInfo);
						result = sellInfo.getDELIVERYORDERCODE()+result;
					}
				}else{
					ctlSellSoInfoDao.upSellFlag(deliveryOrderId);//如果订单已经进入wms，防止重复进入扫描到数据，直接更新ctl库标记。
					result = "wms的货主："+sellInfo.getOWNERCODE()+"已经存在该订单：" + sellInfo.getDELIVERYORDERCODE()+"，订单重新进入 wms处理失败。";
				}
				
		} catch (Exception e) {
			result = "ctl层的发货单 ：\t" + deliveryOrderId+"进入 wms处理失败。" + e;
			log.error(result);
			//TODO 将处理失败的发货单记录到数据库中去。尝试人工参与解决。
			/**
			 * 根据目前考虑到的地方，数据库可以记录表名称、人工参与处理的字段名称（sendflag等标记）。以及需要处理的id，
			 * 可以在界面上做出全表内容的展示。
			 */
			//TODO 如果后期上线短信或微信提醒功能的话，可以在每次往数据库写入失败信息的时候发出电信或微信提醒。
			e.printStackTrace();
			return result;
		}
		
		return result;


	}
	
}
